package com.yuexia.yxim.server.server;

import com.yuexia.yxim.common.bean.msg.User;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * SessionMap
 *
 * @author wjp
 * @date 2020/6/4
 */
@Slf4j
@Data
public final class SessionMap {

    private ConcurrentHashMap<String, ServerSession> map = new ConcurrentHashMap<>();

    private static SessionMap singleInstance = new SessionMap();

    public static SessionMap inst() {
        return singleInstance;
    }

    /**
     * 增加会话
     * @param sessionId
     * @param session
     */
    public void addSession(String sessionId, ServerSession session) {
        map.put(sessionId, session);
        log.info("用户登录：id = {},在线总数 = {}",session.getUser().getUid(), map.size());
    }

    /**
     * 获取session对象
     * @param sessionId
     * @return
     */
    public ServerSession getSession(String sessionId) {
        if (map.contains(sessionId)) {
            return map.get(sessionId);
        }
        return null;
    }

    /**
     * 根据用户id获取session
     * @param userId
     * @return
     */
    public List<ServerSession> getSessionBy(String userId) {
       return map.values()
                   .stream()
                   .filter(s -> s.getUser().getUid().equals(userId))
                   .collect(Collectors.toList());
    }

    /**
     * 删除session
     * @param sessionId
     */
    public void removeSession(String sessionId) {
        if (!map.containsKey(sessionId)) {
          return;
        }
        ServerSession serverSession = map.get(sessionId);
        map.remove(sessionId);
        log.info("用户下线：id = {},在线总数：{}",
                serverSession.getUser().getUid(), map.size());
    }

    public boolean hasLogin(User user) {
        Iterator<Map.Entry<String, ServerSession>> it = map.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry<String, ServerSession> next = it.next();
            User u = next.getValue().getUser();

            if (u.getUid().equals(user.getUid())
               && u.getPlatform().equals(user.getPlatform())) {
                return true;
            }
        }
        return false;
    }

}
